package com.yuanqi.dz.dc.service.impl.aidi;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import pnbclient.helper.StringHelper;
import pnbclient.util.JSONParser;
import pnbclient.util.PnbLogFactory;
import pnblog.PnbLogging;

import com.yuanqi.dz.dc.util.DZConfigRead;
import com.yuanqi.dz.dc.util.DateUtil;
import com.yuanqi.dz.dc.util.MD5;
import com.yuanqitech.advancedpower.powereturn.ExceptionUtil;
import com.yuanqitech.powermop.dz.DZDataInterface;
import com.yuanqitech.powermop.dz.DZInfo;
import com.yuanqitech.powermop.dz.DZInfoArray;

//测试3
@SuppressWarnings("unchecked")
public class AidiDZServiceImpl implements DZDataInterface{

	public static final PnbLogging log = PnbLogFactory.getLogger("DZ_EXT_LOG");

	public  String parkId = "";

	public  String appKey = "";
	
	public  String aidi_dz_address = "";

	
	public DZInfoArray getDZData(String mercharnum, String dzDate) {
		
		long sessionId = System.currentTimeMillis();
		
		DZInfoArray dzInfoArray = new DZInfoArray(); 

		aidi_dz_address = DZConfigRead.getProperties("aidi_dz_address");
		parkId = DZConfigRead.getProperties("parkId");
		appKey = DZConfigRead.getProperties("appKey");

		String timeStamp = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");

		String password = MD5.md5(parkId + appKey + timeStamp).toUpperCase();

		String dzdate = DateUtil.stringFormat(dzDate, "yyyyMMdd", "yyyy-MM-dd");

		String startTime = dzdate + " 00:00:00";
		String endTime = dzdate + " 23:59:59";

		Map<String, Object> DzInPut = new HashMap<String, Object>();
		Map<String, Object> DzOutPut = new HashMap<String, Object>();

		DzInPut.put("parkId", parkId);
		DzInPut.put("password", password);
		DzInPut.put("timeStamp", timeStamp);
		DzInPut.put("outtradeNo", "");
		DzInPut.put("tradeNo", "");
		DzInPut.put("payment", "");
		DzInPut.put("startTime", startTime);
		DzInPut.put("endTime", endTime);
		DzInPut.put("merchantsNo", mercharnum);

		String content = JSONParser.fromObject(DzInPut);
		
		InputStream is=null;
		String respbody=null;
		try{
			log.addDebug("sessionId "+sessionId+" 爱迪 传入JSON格式:"+content);

			CloseableHttpClient httpclient = HttpClients.createDefault();
			HttpPost post=new HttpPost(aidi_dz_address);
			//           post.setRequestBody(content);
			StringEntity stringEntity=new StringEntity(content);
			post.setEntity(stringEntity);

			HttpResponse httpResponse=httpclient.execute(post);
			log.addDebug("sessionId "+sessionId+" 爱迪 Response status code: " + httpResponse.getStatusLine().getStatusCode());
			is=httpResponse.getEntity().getContent();
			respbody=IOUtils.toString(is,"utf-8");
			log.addDebug("sessionId "+sessionId+" 爱迪 Response content: " + respbody);

			if(StringHelper.isEmpty(respbody)){
				dzInfoArray.setRc("0");
				dzInfoArray.setErrormsg("爱迪科技未返回数据");
				return dzInfoArray;
			}

			DzOutPut = (Map<String, Object>) JSONParser.toObject(respbody, Map.class);

			if(null == DzOutPut || DzOutPut.isEmpty() ){
				dzInfoArray.setRc("0");
				dzInfoArray.setErrormsg("爱迪科技未返回数据");
				return dzInfoArray;
			}

			String rc =  String.valueOf(DzOutPut.get("resCode")) ;

			if("0".equals(rc)){
                  DZInfo[] dzinfos = getDzInfos(DzOutPut);
                  dzInfoArray.setDzInfo(dzinfos);
                  dzInfoArray.setRc("1");
			}else{
				dzInfoArray.setRc("0");
				dzInfoArray.setErrormsg("爱迪科技返回数据失败");
				return dzInfoArray;
			}

		} catch (UnsupportedEncodingException e) {
			log.addError(e);
			dzInfoArray.setRc("0");
			dzInfoArray.setErrormsg("调用爱迪科技接口异常");
			return dzInfoArray;
		} catch (ClientProtocolException e) {
			log.addError(e);
			dzInfoArray.setRc("0");
			dzInfoArray.setErrormsg("调用爱迪科技接口异常");
			return dzInfoArray;
		} catch (IOException e) {
			log.addError(e);
			dzInfoArray.setRc("0");
			dzInfoArray.setErrormsg("调用爱迪科技接口异常");
			return dzInfoArray;
		}finally{
			ExceptionUtil.close(is); 
		}

		return dzInfoArray;
	}

	public  DZInfo[] getDzInfos(Map<String, Object> DzOutPut){

		List<Map<String, Object>> list = (List<Map<String, Object>>) DzOutPut.get("data");
		if(null==list || list.size()==0) return null;
		
		DZInfo[] dzinfos = new DZInfo[list.size()];
		Map<String, Object> data = new HashMap<String, Object>();
		DZInfo dzinfo = new DZInfo();
		for (int i = 0; i < list.size(); i++) {
			data = list.get(i);
			dzinfo = getDzInfo(data);
			dzinfos[i] = dzinfo;
		}
		return dzinfos;		
	}


	public DZInfo getDzInfo(Map<String, Object> data){
		
		DZInfo dzinfo = new DZInfo();
		dzinfo.setReferNum(String.valueOf(data.get("tradeNo")));
		dzinfo.setAmount(Float.valueOf(String.valueOf(data.get("collectFee"))));
		String trdatetime = String.valueOf(data.get("leaveTime"));
		trdatetime = trdatetime.substring(0, trdatetime.length()-2);
		dzinfo.setTrDateTime(trdatetime);
		dzinfo.setTranCode("S1");
		dzinfo.setExt6(String.valueOf(data.get("outTradeNo")));
		dzinfo.setTranCardNum(String.valueOf(data.get("enterPlate")));
        dzinfo.setExt1(String.valueOf(data.get("timeSpan")));
        dzinfo.setExt2(String.valueOf(data.get("id")));
        dzinfo.setExt3(String.valueOf(data.get("enterTime")));
		return dzinfo;
	}

	public static void main(String[] args) {
		DZInfoArray dz = 	new AidiDZServiceImpl().getDZData("1495755452", "20180313");
		if(null!=dz){
			DZInfo[] ds = dz.getDzInfo();
			
			if(null!=ds && ds.length > 0){
				for (int i = 0; i < ds.length; i++) {
					System.out.println(ds[i]);
				}
			}
		}
		
   /*     String s=  "2018-03-01 22:00:22.0";
        s= s.substring(0, s.length()-2);
        System.out.println(s);*/

	}

}
